package oldCode;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ImagePanel extends JPanel
{
    /**
     * I don't know what this is for, but Eclipse wants it all the time.
     */
    private static final long serialVersionUID = 6439953650134167317L;
    private BufferedImage displayImage;
    private Dimension imageDimensions;
    private Point imageOrigin;

    
    public ImagePanel(String imagePath)
    {
        try
        {
            displayImage = ImageIO.read(new File(imagePath));
            
            if( displayImage == null )
                throw new NullPointerException();
            
            imageDimensions = new Dimension();
            imageDimensions.setSize(displayImage.getWidth(), displayImage.getHeight());
            this.setPreferredSize(imageDimensions);
            this.setMinimumSize(this.getPreferredSize());
            this.setMaximumSize(this.getPreferredSize());
            
            imageOrigin = new Point(0, 0);
            
        } catch ( IOException e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NullPointerException e) 
        {
            JOptionPane.showMessageDialog(this, "Invalid file type: " + imagePath , "Error Opening File", JOptionPane.ERROR_MESSAGE );
        }
    }
    
    /**
     * @return the displayImage
     */
    public BufferedImage getDisplayImage()
    {
        return displayImage;
    }

    /**
     * @return the imageDimensions
     */
    public Dimension getImageDimensions()
    {
        return imageDimensions;
    }

    /**
     * @return the imageOrigin
     */
    public Point getImageOrigin()
    {
        return imageOrigin;
    }

    protected void paintComponent( Graphics g )
    {
        imageOrigin.x = ( getWidth() - imageDimensions.width)/2;
        imageOrigin.y = ( getHeight() - imageDimensions.height)/2;
        g.drawImage(displayImage, imageOrigin.x, imageOrigin.y, this);
        
        // Trying to pack? I don't know what this does, but it resizes the frame to fit the image.
        JFrame mainFrame = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, this);
        if( mainFrame != null )
        {
            mainFrame.pack();
        }
    }
}
